package org.shuma.goods.controller;


import com.alipay.sofa.runtime.api.annotation.SofaReference;
import com.alipay.sofa.runtime.api.annotation.SofaReferenceBinding;
import com.google.common.base.Preconditions;
import org.shuma.goods.common.BaseResponse;
import org.shuma.goods.common.ErrorCode;
import org.shuma.goods.common.ResultUtils;
import org.shuma.goods.domain.DTO.ProductDTO;
import org.shuma.goods.domain.DTO.UpdateStatus;
import org.shuma.goods.domain.entity.ProductBasicInfo;
import org.shuma.goods.domain.entity.ProductDetailsInfo;
import org.shuma.goods.domain.entity.ProductType;
import org.shuma.goods.exception.BusinessException;
import org.shuma.goods.service.ProductBasicInfoService;
import org.shuma.goods.service.ProductBasicInfoServiceByXingWang;
import org.shuma.goods.service.ProductDetailsInfoServiceByXingWang;
import org.shuma.goods.service.ProductTypeService;
import org.shuma.proxy.facade.Proxy;
import org.shuma.record.domain.vo.OperationRecordVO;
import org.shuma.record.facade.RecordsFacade;
import org.shuma.user.facade.UserFacade;
import org.shuma.user.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static org.shuma.goods.contant.GoodsConstant.*;
import static org.shuma.goods.contant.UserConstant.ADMIN_STATUS;
import static org.shuma.goods.contant.UserConstant.USER_STATUS;

@RestController
@RequestMapping("/goods")
public class GoodsController {
    /**
     * 调用user服务
     */
    @SofaReference(interfaceType = UserFacade.class, uniqueId = "${service.user.unique.id}",
            binding = @SofaReferenceBinding(bindingType = "bolt"))
    private UserFacade userFacade;


    @SofaReference(interfaceType = Proxy.class, uniqueId = "${service.proxy.unique.id}",
            binding = @SofaReferenceBinding(bindingType = "bolt"))
    private Proxy proxy;

    @SofaReference(interfaceType = RecordsFacade.class, uniqueId = "${service.record.unique.id}",
            binding = @SofaReferenceBinding(bindingType = "bolt"))
    private RecordsFacade recordsFacade;


    @Resource ProductBasicInfoService productBasicInfoService;
    @Autowired
    private ProductBasicInfoServiceByXingWang productBasicInfoServiceByXingWang;
    @Autowired
    private ProductDetailsInfoServiceByXingWang productDetailsInfoServiceByXingWang;


    @Resource
    private ProductTypeService productTypeService;



    /**
     * 添加商品
     * @return
     */
    /*@PostMapping("/upload")
    public ResponseEntity<String> handleFormData(
           @RequestParam("title") String title, // 普通表单字段
           @RequestPart("file") MultipartFile file // 文件字段) {*/
    @PostMapping
    public BaseResponse<String> addGoods(
            @RequestPart("file") MultipartFile file,
            @ModelAttribute("productDTO") ProductDTO productDTO,
            @RequestHeader("Authorization") String token) {
        UserVo userVo = userFacade.getUserInfoByToken(token).getData();
        if(userVo.getUserRole()!=0){
            throw new BusinessException(ErrorCode.NULL_AUTH);
        }
        try {
            Preconditions.checkNotNull(productDTO.getProductName(),"商品名称不能为空");
            Preconditions.checkNotNull(productDTO.getDescription(),"商品描述不能为空");
            Preconditions.checkNotNull(productDTO.getCategory(),"商品类型不能为空");
            Preconditions.checkNotNull(productDTO.getProductTypeId(),"商品分类不能为空");
            Preconditions.checkNotNull(productDTO.getSupplierName(),"供应商不能为空");
            Preconditions.checkNotNull(productDTO.getSupplierPhone(),"供应商电话不能为空");
            Preconditions.checkNotNull(productDTO.getServiceGuarantee(),"服务保障不能为空");
            Preconditions.checkNotNull(productDTO.getTimeOn(),"商品上线时间不能为空");
            Preconditions.checkNotNull(productDTO.getTimeOff(),"商品下线时间不能为空");
        } catch (Exception e){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Date timeOn = productDTO.getTimeOn();
        Date timeOff = productDTO.getTimeOff();
        if (timeOn.after(timeOff)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"商品上线时间必须早于或等于商品下线时间");
        }
        Date now = new Date();
        if (timeOn.before(now) || timeOff.before(now)) {
            throw new IllegalArgumentException("商品上线和下线时间必须为未来的时间");
        }
        productDTO.setCreator(userVo.getId());
        try {
            ProductBasicInfo basicInfo = productBasicInfoServiceByXingWang.insert(productDTO, file);

            OperationRecordVO operationRecordVO = new OperationRecordVO();
            operationRecordVO.setOperationState(4);
            operationRecordVO.setOperatorId(userVo.getId());
            operationRecordVO.setProductId(basicInfo.getProductId());
            recordsFacade.addRecord(operationRecordVO);


        } catch (Exception e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return ResultUtils.success("","操作成功");
    }
    /**
     * 删除商品
     * @return
     */
    @DeleteMapping("/delete")
    public BaseResponse<String> deleteGoods(@RequestParam("pids") String pids,
                                            @RequestHeader("Authorization") String token) {
        UserVo userVo = userFacade.getUserInfoByToken(token).getData();
        if(userVo.getUserRole()!=0){
            throw new BusinessException(ErrorCode.NULL_AUTH);
        }
        Long userId = userVo.getId();
        //根据创建人id查询商品
        List<Long> productIds = productBasicInfoServiceByXingWang.queryByCreatorId(userId);
        if (productIds.isEmpty()){
            throw new BusinessException(ErrorCode.NULL_AUTH);
        }
        if (pids == null || pids.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //将传入的String转换为集合
        List<Long> productIdList = Arrays.stream(pids.split(","))
                .map(String::trim) // 去除可能的空白字符
                .map(Integer::parseInt)// 将字符串转换为整数
                .map(Integer::longValue)
                .collect(Collectors.toList());
        //取两个集合的交集进行删除
        List<Long> list = productIds.stream()
                .filter(productIdList::contains)
                .collect(Collectors.toList());
        if (list.isEmpty()){
            throw new BusinessException(ErrorCode.NULL_AUTH);
        }
        productBasicInfoServiceByXingWang.deleteById(list);
        return ResultUtils.success( "","操作成功");
    }

    /**
     * 更新商品
     *
     * @param productDTO
     * @return
     */
    @PutMapping("/update")
    public BaseResponse<String> updateGoods(@RequestBody ProductDTO productDTO,
                                            @RequestHeader("Authorization") String token) {
        UserVo userVo = userFacade.getUserInfoByToken(token).getData();
        if(userVo.getUserRole()!=0){
            throw new BusinessException(ErrorCode.NULL_AUTH);
        }
        Long userId = userVo.getId();
        List<Long> productIds = productBasicInfoServiceByXingWang.queryByCreatorId(userId);
        boolean exist = productIds.contains(productDTO.getProductId());
        if (!exist){
            throw new BusinessException(ErrorCode.NULL_AUTH);
        }
        int state = productDTO.getProductCheckState();
        if (state != 0 && state != 2 && state != 6 && state!= 3 && state != 5) {
            throw new BusinessException(ErrorCode.FORBIDDEN,"当前商品状态不能修改");
        }
        ProductDetailsInfo productDetailsInfo = new ProductDetailsInfo();
        BeanUtils.copyProperties(productDTO, productDetailsInfo);
        Long pDetailsId = productBasicInfoService.queryById(productDTO.getProductId()).getPDetailsId();
        productDetailsInfo.setPDetailsId(pDetailsId);
        try {
            productDetailsInfoServiceByXingWang.update(productDetailsInfo);
            ProductBasicInfo basicInfo = productBasicInfoServiceByXingWang.update(productDTO);
            OperationRecordVO operationRecordVO = new OperationRecordVO();
            operationRecordVO.setOperationState(4);
            operationRecordVO.setOperatorId(userVo.getId());
            operationRecordVO.setProductId(basicInfo.getProductId());
            recordsFacade.addRecord(operationRecordVO);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"操作失败，请联系管理员");
        }
        return ResultUtils.success( "","操作成功");
    }

    /**
     * 修改商品状态(提交审核、通过审核、驳回审核)
     * @param updateStatus
     * @param userVo
     * @return
     */
    @PostMapping("/product_status")
    public BaseResponse<Boolean> updateStatus(@RequestBody UpdateStatus updateStatus,  @RequestAttribute("userInfo")UserVo userVo) {


        Long userId = userVo.getId();
        Long productId = updateStatus.getProductId();
        Integer productCheckState = updateStatus.getProductCheckState();
        if(productId == null || productCheckState == null ){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数不能为空");
        }

        int RequestStatus = updateStatus.getProductCheckState();

        Boolean bool = new Boolean(false);
        //商品是否存在
        ProductBasicInfo oldProduct = productBasicInfoService.getById(productId);
        if(oldProduct == null){
            throw new BusinessException(ErrorCode.NULL_ERROR,"商品不存在");
        }
        List<Long> proxyIds = proxy.getProxy(productId);

        //只能修改自己创建或修改的商品状态
        if(!userId.equals(oldProduct.getCreator()) && !proxyIds.contains(userId)){
            throw new BusinessException(ErrorCode.NULL_AUTH);
        }

        //管理员的非法操作
        if(userVo.getUserRole() == ADMIN_STATUS){

            if(RequestStatus == REJECT_STATUS || RequestStatus == PASS_STATUS){
                bool = productBasicInfoService.updateStatus(updateStatus,userVo);
            }else{
                throw new BusinessException(ErrorCode.NULL_AUTH,"不符合管理员的操作");
            }
        }
        //小二的非法操作
        if(userVo.getUserRole() == USER_STATUS){
            if(RequestStatus == CHECK_ING){
                bool = productBasicInfoService.updateStatus(updateStatus,userVo);
            }else{
                throw new BusinessException(ErrorCode.NULL_AUTH,"不符合小二的操作");

            }
        }

        OperationRecordVO operationRecordVO = new OperationRecordVO();
        operationRecordVO.setOperatorId(userId);
        operationRecordVO.setRemark(updateStatus.getRemark());
        operationRecordVO.setProductId(productId);

        //发起审核
        if(updateStatus.getProductCheckState() == CHECK_ING){
            operationRecordVO.setOperationState(3);
        }
        //审核通过
        if(updateStatus.getProductCheckState() == PASS_STATUS){
            operationRecordVO.setOperationState(2);
        }
        //审核驳回
        if(updateStatus.getProductCheckState() == REJECT_STATUS){
            operationRecordVO.setOperationState(5);
        }

        recordsFacade.addRecord(operationRecordVO);


        return ResultUtils.success(bool);

    }


    /**
     * 查询商品类型
     * @return
     */
    @GetMapping("/product_type")
    public BaseResponse<List<String>> productType(){


        List<ProductType> productTypes = productTypeService.list();

        // 使用 Stream API 获取 name 属性并收集到一个新的列表中
        List<String> productTypeNames = productTypes.stream()
                .map(ProductType::getProductName)
                .collect(Collectors.toList());


        return ResultUtils.success(productTypeNames);
    }


}
